package com.pzh.logistics.controller;


import com.pzh.logistics.common.ResultVO;
import com.pzh.logistics.exception.GlobalException;
import com.pzh.logistics.exception.ResultEnum;
import com.pzh.logistics.util.ResultVOUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@CrossOrigin
@RequestMapping("/home")
public class HomeController {

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public ResultVO login(String username, String password) {
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                throw new GlobalException(ResultEnum.USER_NOT_EXIST);
            } catch (IncorrectCredentialsException ice) {
                throw new GlobalException(ResultEnum.USER_CHECK_ERROR);
            } catch (AuthenticationException ae) {
                throw new GlobalException(ResultEnum.CHECK_ULTRA_VIRES);
            }
        }
        return ResultVOUtil.success();
    }

    /**
     * 用户登出
     * @return
     */
    @GetMapping(value = "/logout")
    public ResultVO logout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return ResultVOUtil.success();
    }

    /**
     * 权限验证失败的跳转页面
     * @return
     */
    @GetMapping("unauth")
    public ResultVO unauth(){
        throw new GlobalException(ResultEnum.UNLOGIN);
    }
}
